package com.ldc.commonlibs.common

import com.google.gson.JsonParseException
import com.google.gson.annotations.SerializedName
import okio.IOException
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

data class RspModel<out T>(
    @SerializedName("errorCode")
    val errorCode: Int = -1,
    @SerializedName("errorMsg")
    val errorMsg: String,
    @SerializedName("data")
    val data: T? = null,
) {
    fun isSuccess(): Boolean {
        return errorCode == CODE_SUCCESS && data != null
    }

    fun isSuccessIgnoreData(): Boolean {
        return errorCode == CODE_SUCCESS
    }

    companion object {
        const val CODE_SUCCESS = 0

        // 网络状态码
        private const val CODE_NET_ERROR = 4000
        private const val CODE_TIMEOUT = 4080
        private const val CODE_JSON_PARSE_ERROR = 4010
        private const val CODE_SERVER_ERROR = 5000

        fun <T> fromException(e: Throwable): RspModel<T> {
            return when (e) {
                is HttpException -> {
                    RspModel(CODE_NET_ERROR, "网络异常(${e.code()},${e.message()})")
                }
                is UnknownHostException -> {
                    RspModel(CODE_NET_ERROR, "网络连接失败，请检查后再试")
                }
                is ConnectTimeoutException, is SocketTimeoutException -> {
                    RspModel(CODE_TIMEOUT, "请求超时，请稍后再试")
                }
                is IOException -> {
                    RspModel(CODE_NET_ERROR, "网络异常(${e.message})")
                }
                is JsonParseException, is JSONException -> {
                    // Json解析失败
                    RspModel(CODE_JSON_PARSE_ERROR, "数据解析错误，请稍后再试")
                }
                else -> {
                    RspModel(CODE_SERVER_ERROR, "系统错误(${e.message})")
                }
            }
        }
    }
}
